package com.doyoo.controller;

import com.doyoo.common.ResponseResult;
import com.doyoo.entity.JobInfo;
import com.doyoo.service.JobInfoService;
import io.kubernetes.client.PodLogs;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Tag(name = "Pod(K8S)")
@RequestMapping
@RestController
public class PodController {
    @Autowired
    private CoreV1Api coreV1Api;

    @Autowired
    private PodLogs podLogs;

    @Autowired
    private JobInfoService jobInfoService;


    @Operation(summary = "根据jobName查询pod日志")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "jobId", value = "作业id", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "jobName", value = "作业名称，注意这里是k8s中的job名称", dataTypeClass = String.class)})
    @GetMapping("/pod-logs")
    public ResponseResult<List<String>> getLog(@RequestParam Integer jobId,
                                           @RequestParam String jobName) throws ApiException, IOException {
        JobInfo jobInfo = jobInfoService.getById(jobId);
        if (jobInfo == null) {
            throw new RuntimeException("未找到作业");
        }
        String namespace = StringUtils.defaultString(jobInfo.getEnvs(), "default");

        String labelSelector = "job-name=" + jobName;
        V1PodList v1PodList = coreV1Api.listNamespacedPod(namespace, "false", null, null, null, labelSelector, null, null, null, null);
        List<V1Pod> podListItems = v1PodList.getItems();
        List<String> logList = new ArrayList<>(podListItems.size());
        for (V1Pod v1Pod : v1PodList.getItems()) {
            InputStream is = podLogs.streamNamespacedPodLog(v1Pod);
            String log = StreamUtils.copyToString(is, StandardCharsets.UTF_8);
            logList.add(log);
        }
        return ResponseResult.success(logList);
    }
}
